package com.woniu.fly.fairmall.db.service;


import com.github.pagehelper.PageHelper;
import com.woniu.fly.fairmall.db.dao.FairmallRoleDao;
import com.woniu.fly.fairmall.db.entity.FairmallRole;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 角色表(FairmallRole)表服务实现类
 *
 * @author makejava
 * @since 2020-04-02 13:45:03
 */
@Service("fairmallRoleService")
public class FairmallRoleService {
    @Resource
    private FairmallRoleDao fairmallRoleDao;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    public FairmallRole queryById(Integer id) {
        return this.fairmallRoleDao.queryById(id);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit 查询条数
     * @return 对象列表
     */
    public List<FairmallRole> queryAllByLimit(int offset, int limit) {
        return this.fairmallRoleDao.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param fairmallRole 实例对象
     * @return 实例对象
     */
    public FairmallRole insert(FairmallRole fairmallRole) {
        this.fairmallRoleDao.insert(fairmallRole);
        return fairmallRole;
    }

    /**
     * 修改数据
     *
     * @param fairmallRole 实例对象
     * @return 实例对象
     */
    public FairmallRole update(FairmallRole fairmallRole) {
        this.fairmallRoleDao.update(fairmallRole);
        return this.queryById(fairmallRole.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    public boolean deleteById(Integer id) {
        return this.fairmallRoleDao.deleteById(id) > 0;
    }

    public Set<String> queryByIds(Integer[] roleIds) {
        Set<String> roles = new HashSet<>();
        if(roleIds.length == 0){
            return roles;
        }
        String ids = getInRoleIds(Arrays.asList(roleIds));
        List<FairmallRole> roleList = fairmallRoleDao.queryRoleListByIds(ids);
        for(FairmallRole role : roleList){
            roles.add(role.getName());
        }
        return roles;
    }

    public String getInRoleIds(List roleIds) {
         return roleIds.toString().replace("[", "(").replace("]",")");
    }

    public List<FairmallRole> queryListByPage(String name, Integer page, Integer limit) {
        FairmallRole role = new FairmallRole();
        role.setName(name);
        PageHelper.startPage(page, limit);
        return fairmallRoleDao.queryAll(role);
    }

    public boolean checkExist(String name) {
        FairmallRole role = new FairmallRole();
        role.setName(name);
        List<FairmallRole> roles = fairmallRoleDao.queryAll(role);
        return !CollectionUtils.isEmpty(roles);
    }
}
